<template>
  <!-- 运营管理-订单管理页面 -->

  <!-- 查询表单区块 -->
  <el-card>
    <el-row :gutter="20">
      <!-- 订单号 -->
      <el-col :span="6">
        <el-input placeholder="请输入订单号" v-model="form.orderNo"></el-input>
      </el-col>

      <!-- 订单状态 -->
      <el-col :span="6">
        <!-- 下拉框 -->
        <el-select placeholder="订单状态" v-model="form.status">
          <el-option label="全部" :value="1"></el-option>
          <el-option label="进行中" :value="2"></el-option>
          <el-option label="已完成" :value="3"></el-option>
          <el-option label="异常" :value="4"></el-option>
        </el-select>
      </el-col>

      <!-- 设备编号 -->
      <el-col :span="6">
        <el-input placeholder="设备编号" v-model="form.on"></el-input>
      </el-col>

      <!-- 查询 / 重置按钮 -->
      <el-col :span="6">
        <el-button type="primary" @click="loadData()">查询</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </el-col>

      <!-- 站点名称 -->
      <el-col :span="6" class="mt">
        <el-input placeholder="请输入站点名称" v-model="form.name"></el-input>
      </el-col>

      <!-- 日期范围 -->
      <el-col :span="6" class="mt">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="/"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          @change="handleChange"
          value-format="YYYY-MM-DD"
        />
      </el-col>
    </el-row>
  </el-card>

  <!-- 按钮区块 -->
  <el-card class="mt">
    <el-button type="danger" :disabled="!selectionList.length" @click="handleBatchDelete"
      >批量删除</el-button
    >
    <el-button
      type="primary"
      icon="Download"
      :disabled="!selectionList.length"
      @click="exportToExcel()"
      >导出订单数据到Excel</el-button
    >
  </el-card>

  <!-- 表格,分页区块 -->
  <el-card class="mt">
    <!-- 表格区块 -->
    <el-table :data="dataList" v-loading="loading" @selection-change="handleSelectChange">
      <!-- 表格多选 -->
      <el-table-column type="selection" width="55"></el-table-column>
      <!-- 表格序号 -->
      <el-table-column type="index" label="序号" width="80"></el-table-column>
      <el-table-column label="订单号" prop="orderNo"></el-table-column>
      <el-table-column label="设备编号" prop="equipmentNo"></el-table-column>
      <el-table-column label="订单日期" prop="date"></el-table-column>
      <el-table-column label="开始时间" prop="startTime"></el-table-column>
      <el-table-column label="解释时间" prop="endTime"></el-table-column>
      <el-table-column label="金额" prop="money"></el-table-column>
      <el-table-column label="支付方式" prop="pay"></el-table-column>
      <el-table-column label="订单状态" prop="status">
        <!-- 使用插槽,根据数值显示对应订单状态 -->
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.status === 2">进行中</el-tag>
          <el-tag type="primary" v-else-if="scope.row.status === 3">已完成</el-tag>
          <el-tag type="warning" v-else-if="scope.row.status === 4">异常</el-tag>
        </template>
      </el-table-column>
      <!-- 操作按钮 - 详情 / 删除 -->
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleDetail(scope.row)"
            >详情</el-button
          >
          <el-button type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="mt mb fr"
      v-model:current-page="pageInfo.page"
      v-model:page-size="pageInfo.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      bakeground
      layout="total, sizes, prev, pager, next, jumper"
      :total="totals"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
// 引入 useHttp
import { useHttp } from "@/hokes/useHttp";
// 引入页签组件
import { useTabsStore } from "@/store/tabs";

// 规定查询参数类型
interface SearchType {
  orderNo: string; //订单号
  status: number; //订单状态
  on: string; //设备编号
  name: string; //站点名称
  startDate: string; // 开始日期
  endDate: string; // 结束日期
}
// 查询参数 - 双向绑定数据
const form = ref<SearchType>({
  orderNo: "", //订单号
  status: 1, //订单状态
  on: "", //设备编号
  name: "", //站点名称
  startDate: "", // 开始日期
  endDate: "", // 结束日期
});
/**
 * 1:注意,这种日期范围选择器 v-model绑定的值必须是一个数组
 * 2:后端一般要求前端传2个值,开始时间和结束时间,所以组件的双向绑定值必须单独定义一个数组
 */
const date = ref([]); // 日期范围
// 日期范围选择器的点击事件
const handleChange = (value: string[]) => {
  // 赋值起始日期
  form.value.startDate = value[0];
  // 赋值结束日期
  form.value.endDate = value[1];
};

// 规定表格数据类型
interface TableDataType {
  orderNo: string; // 订单号
  equipmentNo: string; // 设备编号
  date: string; // 订单日期
  startTime: string; // 开始时间
  endTime: string; // 结束时间
  money: number; // 金额
  pay: string; // 支付方式
  status: number; // 订单状态
}

// 调用 useHttp,要传入2个参数,1是接口地址,2是查询区块的双向绑定数据(当前页面是:form),并用结构赋值获取里面的数据和方法
const {
  dataList,
  loading,
  totals,
  pageInfo,
  loadData,
  handleCurrentChange,
  handleSizeChange,
  resetPagination,
} = useHttp<TableDataType>("/order/orderList", form);

// 重置按钮方法
const resetForm = () => {
  form.value = {
    orderNo: "",
    status: 1,
    on: "",
    name: "",
    startDate: "",
    endDate: "",
  };
  date.value = [];
  resetPagination();
};

// 处理表格选中项变化
const selectionList = ref<SearchType[]>([]);
const handleSelectChange = (selection: SearchType[]) => {
  selectionList.value = selection;
};

// 引入相关接口 API
import { batchDeleteApi } from "@/api/operation";
import { ElMessage } from "element-plus";

// 批量删除按钮方法
const handleBatchDelete = async () => {
  try {
    // 获取选中的订单号,并拼接成字符串
    const orders = selectionList.value.map((item: SearchType) => item.orderNo).join(",");
    console.log(orders);
    // 调用批量删除接口
    const res = await batchDeleteApi(orders);
    if (res.code === 200) {
      // 提示删除成功
      ElMessage.success("批量删除成功");
      // 重新加载数据
      loadData();
    } else {
      ElMessage.error(res.message || "批量删除失败");
    }
  } catch (error) {
    ElMessage.error("批量删除异常");
  }
};

// 获取路由对象
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
const tabsStore = useTabsStore();
const { addTab, setCurrentTab } = tabsStore;
// 详情按钮方法
const handleDetail = (row: TableDataType) => {
  // 获取订单号
  const orderNo = row.orderNo;
  // 添加页签
  addTab("订单详情", "/operations/detail", "Share");
  // 设置当前页签
  setCurrentTab("订单详情", "/operations/detail");
  // 跳转到详情页面
  router.push("/operations/detail?orderNo=" + orderNo);
};
// 监听当前路由变化
watch(
  () => route.name,
  (to, from) => {
    console.log("当前页面:", to, "来源页面:", from);
    if (to == "Orders" && from !== "Detail") {
      loadData();
    }
  }
);

// 引入 xlsx 库和 file-saver 库
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";

const exportToExcel = () => {
  const ws = XLSX.utils.json_to_sheet(dataList.value); // 把数据转换成工作表格式
  const wb = XLSX.utils.book_new(); // 创建一个新的工作簿
  XLSX.utils.book_append_sheet(wb, ws, "订单数据"); // 将工作表添加到工作簿中,并命名
  const wbout = XLSX.write(wb, { bookType: "xlsx", type: "array" }); // 将工作簿写入为二进制数组
  const blob = new Blob([wbout], { type: "application/octet-stream" }); // 创建一个 Blob 对象
  saveAs(blob, "订单数据.xlsx"); // 使用 file-saver 库保存文件
};
</script>

<style scoped></style>
